package com.example.demo.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;

/**
 * @Author: ElonChung
 * @Date:
 * @Description:
 */
@Slf4j
public class MyRealm extends AuthorizingRealm {
    @Lazy
    @Resource
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("执行了授权AuthenticationInfo");
        // 使用了缓存（ehcache） 当第一次登录时需要执行以下授权
        log.info("使用了缓存（ehcache） 当第一次登录时需要执行以下授权，之后就不用设置，除非缓存清理，退出时要清理缓存");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addStringPermission("user:add");
        //获取当前登录的对象
        Subject subject = SecurityUtils.getSubject();

//        System.out.println(subject.getPrincipal());

        User currentUser = (User) subject.getPrincipal();
        info.addStringPermission(currentUser.getPrams());
//        System.out.println(info.getStringPermissions().toArray());
//        super.clearCache(principals);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("执行了认证AuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("name", userToken.getUsername());
        User user = userService.getOne(userWrapper);
        if (user != null) {
            Subject currentSubject = SecurityUtils.getSubject();
            Session session = currentSubject.getSession();
            session.setAttribute("userInfo", user);
            //三十分钟失效
            session.setTimeout(1800 * 1000);
            return new SimpleAuthenticationInfo(user, user.getPwd(), "");
        }
        return null;
    }

    /**
     * 清除缓存 修改用户信息时调用
     */
    public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }

}
